<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/26 0026
 * Time: 下午 7:04
 */
namespace app\api\controller;

use app\admin\model\Tenant;
use app\common\BaseHelper;
use app\common\model\Useraddress;
use app\common\validate\AddressNew;
use app\api\service\Token as TokenService;
use app\common\model\User;
use app\lib\enum\ScopeEnum;
use app\lib\exception\AddressException;
use app\lib\exception\ForbiddenException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;

class Address extends BaseController {

    //前置方法
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only'=>'createOrUpdateAddress']
    ];

    //访问createOrUpdateAddress的前置方法，判断是否有权限访问该接口


    public function createOrUpdateAddress($addressid=''){
        $validate = new AddressNew();
        $validate->goCheck();

        // 根据Token来获取uid
        // 根据uid来查找用户数据，判断用户是否存在，如果不存在抛出异常。
        // 获取用户从客户端提交来的地址信息

        $uid = TokenService::getCurrentUid();
        $tenantid = TokenService::getTenantid();
        $user = User::get($uid);
        $tenant = Tenant::get($tenantid);
        if(!$user){
            throw new UserException();
        }
        if(!$tenant){
            throw new UserException([
                'msg' => '商户不存在'
            ]);
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $useraddressModel = new Useraddress();
        if(empty($addressid)){
            $dataArray['id'] = BaseHelper::getUUID();
            $dataArray['userId']= $uid;
            $dataArray['tenantId'] = $tenantid;

            //新增地址
            //$user->address()->save($dataArray);
            $useraddressModel->save($dataArray);
        }else{
            //修改地址

            $address = $useraddressModel->where(['id'=>$addressid,'userId'=>$user->id])->find();
            if(!$address){
                throw new AddressException();
            }
            $address->save($dataArray);


        }
        return new SuccessMessage();

    }
}